//
//  ITGCDVC.m
//  InduceTool
//
//  Created by 冯琰琰 on 2022/1/28.
//  Copyright © 2022 魏延龙. All rights reserved.
//

#import "ITGCDVC.h"

@interface ITGCDVC ()

@end

@implementation ITGCDVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
//    [self semaphoreTest];
//    [self conditionLock];
    
    [self gcdTest];
}

-(void)semaphoreTest {
    dispatch_semaphore_t sem = dispatch_semaphore_create(1);
    for (int i = 0; i < 10; i ++) {
        dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
        [[[NSThread alloc] initWithBlock:^{
            NSLog(@"---- i :%d", i);
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"---- i ------");
                dispatch_semaphore_signal(sem);
            });
        }] start] ;
    }
    
    NSLog(@"----------");
//    dispatch_semaphore_t sem = dispatch_semaphore_create(0);
//    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
//    NSLog(@"dispatch_semaphore_t ");
//    dispatch_semaphore_signal(sem);
    
    
}

-(void)conditionLock{
    
    NSConditionLock *conlock = [[NSConditionLock alloc] initWithCondition:1];
    
    [conlock lockWhenCondition:1];
    [[[NSThread alloc] initWithBlock:^{
        NSLog(@"---- +++ i :%d", 1);
        [conlock unlockWithCondition:2];
    }] start] ;
    
    [conlock lockWhenCondition:2];
    [[[NSThread alloc] initWithBlock:^{
        NSLog(@"---- +++i :%d", 2);
        [conlock unlockWithCondition:3];
    }] start] ;
    
    [conlock lockWhenCondition:3];
    [[[NSThread alloc] initWithBlock:^{
        NSLog(@"---- +++i :%d", 3);
        [conlock unlockWithCondition:4];
    }] start] ;
    [conlock lockWhenCondition:4];
    NSLog(@"---- +++i :%d", 100);
    [conlock unlock];
    NSLog(@"---- +++i :%d", 1011);
//    NSConditionLock *conlock = [[NSConditionLock alloc] initWithCondition:1];
//    [conlock lockWhenCondition:2];
//    NSLog(@"NSConditionLock");
//    [conlock unlockWithCondition:2];
    
}
//NSConditionLock

-(void)gcdTest {
    dispatch_semaphore_t sem = dispatch_semaphore_create(0);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"gcdTest a");
        dispatch_semaphore_signal(sem);
    });
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"gcdTest b");
        dispatch_semaphore_signal(sem);
    });
    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"gcdTest c");
    });
}

@end
